import axios, { InternalAxiosRequestConfig, AxiosInstance, AxiosResponse } from 'axios';

import { message } from 'ant-design-vue';

const showDebug = false;

const axiosInstance: AxiosInstance = axios.create({
  baseURL: 'http://localhost:8080',
  timeout: 5 * 1000,
});
function printRequestInfo(config: InternalAxiosRequestConfig) {
  if (showDebug) {
    console.groupCollapsed('%c%s %c请求参数', 'color: blue;', config.url, 'color:black');
    const requestMethod = config.method;
    const requestHeader = config.headers;
    console.info('请求方法:%s', requestMethod);
    console.info('请求头:%o', requestHeader);
    let data = null;
    if ('get' === requestMethod) {
      data = config.params;
    }
    if ('post' === requestMethod) {
      data = config.data;
    }
    console.info('请求参数:%o', data);
    console.groupEnd();
  }
}
function printResponseInfo(response: AxiosResponse) {
  if (showDebug) {
    console.groupCollapsed('%c%s %c返回参数', 'color: blue;', response.config.url, 'color:black');
    console.info('状态码:%c%s', 'color: blue;', response.status);
    console.info('返回值:%o', response.data);
    console.groupEnd();
  }
}
function checkStatusCode(response: AxiosResponse) {
  const statusCode = response.data.code;
  if (statusCode === 10000) {
      return;
  } else{
    throw new Error(response.data.message)
  }
}

// 添加请求拦截器
axiosInstance.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    let authorization = null;
    authorization = localStorage.getItem('access_token') ? `Token ${localStorage.getItem('access_token')}` : null;
    config.headers.Authorization = authorization;
    printRequestInfo(config);
    return config;
  },
  (error: any) => {
    return Promise.reject(error);
  }
);
// 添加响应拦截器
axiosInstance.interceptors.response.use(
  (response: AxiosResponse) => {
    try {
      checkStatusCode(response);
    } catch (error) {
      console.log(response.data.message);
    }
    printResponseInfo(response);
    return response;
  },
  async (error: any) => {
    console.log('error', error);
    return Promise.reject(error);
  }
);
export default axiosInstance;
